package com.dituhui.tool.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 读取HTTP服务内容的工具类
 * 
 * @author liweigu
 * 
 */
public class HttpTool {
	// POST方法
	private static String POST = "POST";
	// 连接超时时间：5秒
	public static int ConnectTimeout = 5000;
	// 读取超时时间：60秒
	public static int ReadTimeout = 60000;

	/**
	 * 用GET方法获取内容
	 * 
	 * @param path
	 *            URL路径
	 * @param param
	 *            URL参数
	 * @return 服务返回内容
	 * @throws IOException
	 */
	public static String getContentByGET(String path, String param) throws IOException {
		// 如果用GET方法，就把参数带到url path上。
		if (param != null) {
			path = path + "?" + param;
		}
		return getContent(path, null);
	}

	/**
	 * 用POST方法获取内容
	 * 
	 * @param path
	 *            URL路径
	 * @param param
	 *            URL参数
	 * @return 服务返回内容
	 * @throws IOException
	 */
	public static String getContentByPOST(String path, String param) throws IOException {
		return getContent(path, param);
	}

	private static String getContent(String path, String param) throws IOException {
		// 打开连接
		URL url = new URL(path);
		URLConnection urlConnection = url.openConnection();
		HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
		httpUrlConnection.setConnectTimeout(ConnectTimeout);
		httpUrlConnection.setReadTimeout(ReadTimeout);

		if (param != null) {
			// 以POST方式处理
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestMethod(POST);

			// 发送post请求
			OutputStream outputStream = httpUrlConnection.getOutputStream();
			PrintWriter printWriter = new PrintWriter(outputStream);
			if (param != null) {
				printWriter.write(param);
			}
			printWriter.flush();
			printWriter.close();
			outputStream.close();
		} else {
			// 默认以GET方式处理
		}

		// 接收处理结果反馈
		String resultString = "";
		// long startTime = System.currentTimeMillis();
		InputStream inputStream = httpUrlConnection.getInputStream();
		// long endTime = System.currentTimeMillis();
		// System.out.println(endTime - startTime);

		int responseCode = httpUrlConnection.getResponseCode();
		if (responseCode == HttpURLConnection.HTTP_OK) {
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
			String line = bufferedReader.readLine();

			while (line != null) {
				resultString += line;
				line = bufferedReader.readLine();
			}
			bufferedReader.close();
		} else {
			// TODO: 改为日志
			System.out.println("服务返回异常：" + responseCode);
		}
		inputStream.close();
		httpUrlConnection.disconnect();

		return resultString;
	}
}
